package com.mobilebook.properties;

import java.io.File;
import java.io.FileNotFoundException;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;

public class GlobalInitializer implements InitializingBean, BeanFactoryAware {

	private BeanFactory beanFactory;
	private String configPath;
	private GlobalPropertyPlaceholderConfigurer propertyConfigurer;

	public void setGlobalPropertyPlaceholderConfigurer(
			GlobalPropertyPlaceholderConfigurer propertyConfigurer) {
		this.propertyConfigurer = propertyConfigurer;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
		
		Object objPropConf = this.beanFactory.getBean("propertyConfigurer");
		if (objPropConf == null)
			throw new RuntimeException("GlobalInitializer must be used with propertyConfigurer");
		if (! (objPropConf instanceof GlobalPropertyPlaceholderConfigurer))
			throw new RuntimeException("GlobalInitializer must be used with YccGlobalPropertyConfigurer");
		this.propertyConfigurer = (GlobalPropertyPlaceholderConfigurer) (objPropConf);
		this.configPath = propertyConfigurer.getConfigPath();
	}

	public void setConfigPath(String configPath) {
		this.configPath = configPath;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		File log4jFile = new File(configPath, "log4j.properties");
		if (log4jFile.exists()) {
			String log4jFileName = log4jFile.getAbsolutePath(); 
			try {
				org.springframework.util.Log4jConfigurer.initLogging(log4jFileName);
			} catch (FileNotFoundException e) {
				throw new RuntimeException(e);
			}
		}
		
	}

}
